import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/monitor',
    name: 'Monitor',
    component: () => import('../views/Monitor.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 先清除可能存在的无效 token
  if (to.path === '/login') {
    localStorage.removeItem('token')
  }
  
  // 需要认证的页面
  if (to.meta.requiresAuth) {
    if (!token) {
      next({ path: '/login' })
      return
    }
  }
  
  // 已登录用户访问登录/注册页面
  if (token && (to.path === '/login' || to.path === '/register')) {
    next({ path: '/monitor' })
    return
  }
  
  next()
})

export default router 